package hn.cch.framework.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);


    public URLConnection connectURL(String str) {
        URLConnection urlConnection = null;
        URL url = null;

        try {
            url = new URL(str);
            urlConnection = url.openConnection();
        } catch (IOException e) {
            logger.error("Connection open fail");
            e.printStackTrace();
            return urlConnection;
        }

        //logger.info(urlConnection.getDoInput());//true
        //logger.info(urlConnection.getDoOutput());//false
        //能读能写：发送请求|接收响应
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        // 关闭缓存
        urlConnection.setUseCaches(false);
        // 开启长连接
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        // 超时时间设置
        urlConnection.setConnectTimeout(1000);
        urlConnection.setReadTimeout(30 * 1000);



        logger.info("URL connect success");
        return urlConnection;

    }

    public void sendGET(String str) {

    }

    public byte[] sendPOST(String url, byte[] request) {

        //连接
        URLConnection urlConnection = connectURL(url);

        byte[] response = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {//读写
            logger.info("OutputStream write");
            outputStream = urlConnection.getOutputStream();
            outputStream.write(request);

            logger.info("InputStream read");
            inputStream = urlConnection.getInputStream();

            response = new byte[urlConnection.getContentLength()];
            int contentLength = inputStream.read(response);
            logger.info("ContentLength " + contentLength);




        } catch (IOException e) {
            logger.error("POST send fail");
            e.printStackTrace();
        } finally {
            // 关闭
            closeStream(outputStream, inputStream);
        }
        return response;

    }

    public void closeStream(OutputStream outputStream, InputStream inputStream) {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            logger.info("Stream close success");
        } catch (IOException e) {
            logger.error("Stream close fail");
            //e.printStackTrace();
        }
    }
}
